import 'package:demo1/util/GraphqlUtil.dart';
import 'package:flutter/gestures.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:flutter/material.dart';
import 'package:demo1/view/DistrictDetailPage.dart';
import 'package:demo1/dto/districtApi.dart';
import 'package:demo1/dto/district.dart';
import 'package:flutter_speed_dial/flutter_speed_dial.dart';

class DistrictListPage extends StatefulWidget {
  @override
  _DistrictListPage createState() => _DistrictListPage();
}

class _DistrictListPage extends State<StatefulWidget> {
  @override
  Widget build(BuildContext context) {
    return Query( //异步请求数据
        options: QueryOptions(
            documentNode: gql(DistrictApi.queryAllDistricts()),
            pollInterval: 1),
        builder: (QueryResult result,
            {VoidCallback refetch, FetchMore fetchMore}) {
          if (result.loading) { //没有结果返回时， 界面显示转圈圈
            return Center(child: CircularProgressIndicator());
          }
          if (result.hasException) {//请求后台报错时， 界面显示转圈圈
            return Center(child: CircularProgressIndicator());
          }
          //结果成功返回时， 从结果集中取出数据， 循环调用对象的fromJson方法， 解析结果集json为对象集合List<District>
          final List districts = result.data['allDistricts']
              .map<District>((d) => District.fromJson(d))
              .toList();

          //将结果集展示到页面上， 使用ListView.build
          return Scaffold(
              appBar: AppBar(
                title: Text('地区列表'),
                centerTitle: true,
              ),
              body: ListView.builder(
                  padding: const EdgeInsets.all(16),
                  itemCount: districts.length,
                  itemBuilder: (BuildContext context, int index) {
                    //*Dismissible组件，这里主要用来实现滑动删除列表子项
                    return Dismissible(
                      // resizeDuration:Duration(seconds: 1),
                      // movementDuration:Duration(seconds: 1),
                      confirmDismiss: (direction) async {
                        return await showDialog(
                            context: context,
                            builder: (context) {
                              // setState();
                              return AlertDialog(
                                title: Text("刪不刪?"),
                                actions: [
                                  FlatButton(
                                      onPressed: () {
                                        client
                                            .mutate(MutationOptions(
                                                documentNode: gql(
                                                    DistrictApi.delete(
                                                        districts[index].id))))
                                            .then((value) => {
                                                  districts.removeAt(index),
                                                });
                                      },
                                      child: Text(
                                        "確定",
                                        style: TextStyle(color: Colors.red),
                                      )),
                                  FlatButton(
                                      onPressed: () {
                                        Navigator.of(context).pop(false);
                                      },
                                      child: Text("取消",
                                          style: TextStyle(color: Colors.red)))
                                ],
                              );
                            });
                      },
                      key: Key(districts[index].id), //key必须唯一， 这里的id是唯一的
                      dragStartBehavior: DragStartBehavior.down,
                      direction: DismissDirection.startToEnd, //列表项往右滑动实现删除
                      background: Container( //滑动时的背景显示， 这里放一个删除的图片， 并将背景颜色设置为红色
                        padding: const EdgeInsets.only(left: 20),
                        alignment: AlignmentDirectional.centerStart,
                        color: Colors.deepOrange,
                        child: Icon(
                          Icons.delete,
                          color: Colors.white,
                          size: 20,
                        ),
                      ),
                      child: Card(  //开始生成列表中的子项（每一项包含 ： 图标 + 地区名称 + 编辑按钮）
                        child: DistrictRow(district: districts[index]),
                      ),
                    );
                  }),

              //右下角的按钮， 使用了flutter_speed_dial组件包, 包含两个功能按钮（新增与批量删除，
              // 点击新增跳转到详情编辑页面DistrictDetailPage， 点击删除， 将删除列表页面选中的项， 选中项的图标为红色)
              floatingActionButton: SpeedDial(
                backgroundColor: Theme.of(context).primaryColor,
                animatedIcon: AnimatedIcons.menu_close,
                child: Icon(Icons.menu),
                overlayColor: Theme.of(context).primaryColor,
                overlayOpacity: 0.4,
                curve: Curves.bounceIn,
                children: [
                  SpeedDialChild(
                      child: Icon(Icons.delete),
                      // label: "删除",
                      labelStyle: TextStyle(color: Colors.deepOrange),
                      onTap: () {
                        return showDialog(
                            context: context,
                            builder: (context) {
                              // setState();
                              return AlertDialog(
                                title: Text("刪除選中?"),
                                actions: [
                                  FlatButton(
                                      onPressed: () {

                                      },
                                      child: Text(
                                        "確定",
                                        style: TextStyle(color: Theme.of(context).primaryColor),
                                      )),
                                  FlatButton(
                                      onPressed: () {
                                        Navigator.of(context).pop(false);
                                      },
                                      child: Text("取消",
                                          style: TextStyle(color:Theme.of(context).primaryColor)))
                                ],
                              );
                            });
                      },
                      backgroundColor: Colors.deepOrange),
                  SpeedDialChild(
                      child: Icon(Icons.add),
                      // label: "新增",
                      labelStyle:
                          TextStyle(color: Theme.of(context).primaryColor),
                      onTap: () => {
                            Navigator.of(context).push(MaterialPageRoute(
                                builder: (BuildContext context) {
                              return DistrictDetailPage();
                            }))
                          },
                      backgroundColor: Theme.of(context).primaryColor),
                ],
              ));
        });
  }
}

//创建列表中的每一个子项
class DistrictRow extends StatefulWidget {
  District district;

  DistrictRow({Key key, @required this.district}) : super(key: key);

  @override
  _DistrictRowState createState() => _DistrictRowState();
}

class _DistrictRowState extends State<DistrictRow> {

  bool selected; //用来标识列表项是否被选中，默认为不选中false
  Color iconColor; //选中的列表项图标颜色为红色， 默认为灰色Colors.grey

  //初始化状态
  @override
  void initState() {
    selected = false;
    iconColor = Colors.grey;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ListTile(
      onTap: () { //列表项的点击事件， 点击后为选中状态，图标颜色变为红色
        setState(() {
          selected = !selected;
          iconColor = selected ? Colors.deepOrange : Colors.grey;
        });
      },
      selected: selected, //是否选中
      // selectedTileColor: Colors.red,
      title: Text(
        widget.district.name,
        textAlign: TextAlign.start,
        style: TextStyle(fontSize: 18),
      ),
      leading: Icon(
        Icons.account_balance,
        color: iconColor,
      ),
      trailing: InkWell(
        child: Text(
          ' 编辑',
          style: TextStyle(color: Colors.black45, fontSize: 18),
        ),
        onTap: () => { // 点击编辑跳转到详情编辑页面DistrictDetailPage
          Navigator.of(context)
              .push(MaterialPageRoute(builder: (BuildContext context) {
            return DistrictDetailPage(id: widget.district.id);
          }))
        },
      ),
    );
  }
}
